package com.study.storm.storm.bolt;


import com.study.storm.entity.User;
import com.study.storm.service.UserService;
import com.study.storm.utils.GetSpringBean;
import org.apache.storm.task.OutputCollector;
import org.apache.storm.task.TopologyContext;
import org.apache.storm.topology.OutputFieldsDeclarer;
import org.apache.storm.topology.base.BaseRichBolt;
import org.apache.storm.tuple.Fields;
import org.apache.storm.tuple.Tuple;
import org.apache.storm.tuple.Values;

import java.util.Map;
import java.util.Objects;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.LockSupport;

/**
 * @author
 */
public class MonthBolt extends BaseRichBolt {

    private static final long serialVersionUID = 6542256546124282695L;
    private UserService userService;
    private OutputCollector outputCollector;

    @Override
    public void prepare(Map map, TopologyContext arg1, OutputCollector collector) {
        userService = GetSpringBean.getBean(UserService.class);
        this.outputCollector = collector;
    }

    @Override
    public void execute(Tuple tuple) {
        User user = (User) tuple.getValueByField("user");
        if (Objects.isNull(user)) {
            return;
        }
        LockSupport.parkNanos(TimeUnit.SECONDS.toNanos(new Random().nextInt(5)));
        user.setUserName("month");
        System.out.println("MONTH Time：" + System.currentTimeMillis() + "--" + "user:" + user);
        this.outputCollector.emit(new Values(user));
    }


    /**
     * cleanup是IBolt接口中定义,用于释放bolt占用的资源。
     * Storm在终止一个bolt之前会调用这个方法。
     */
    @Override
    public void cleanup() {
        System.out.println("MONTH cleanup");
    }

    @Override
    public void declareOutputFields(OutputFieldsDeclarer arg0) {
        arg0.declare(new Fields("user"));
    }


}